<template>
    <view class="container" :style="themeColor">
        <view class="box">
            <!-- #ifdef MP -->
            <view class="login-wx">
                <view class="business">
                    <text>{{ shopName }}</text>
                </view>
                <view class="apply-tip">
                    <text class="apply-tip-title">申请获得以下权限</text>
                    <text class="apply-tip-desc">获取您的公开信息（昵称、头像，地区）等</text>
                </view>
                <button class="btn btn-success btn-save" @click="authorizeFn">授权登录</button>
            </view>
            <!-- #endif -->
        </view>
        <web-view class="webView" v-if="isShow" ref="webView" :src="url">
            <cover-view class="webView-mark" v-if="isShow && showNav"> </cover-view>
        </web-view>
        <uni-popup ref="popTipApply" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="您当前位置暂时无法注册本平台\n是否申请注册" :before-close="true"
                @close="closeFn('popTipApply')" @confirm="applyFn" confirmText="申请"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="popTipApplyResult" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="申请成功,请耐心等待平台审核" :before-close="true" :showCancel="false"
                @confirm="closeFn('popTipApplyResult')"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="popTipApplyOK" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="您已注册,请耐心等待平台审核" :before-close="true" :showCancel="false"
                @confirm="closeFn('popTipApplyOK')" confirmText="确定"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="popTipApplyAgain" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="平台审核已拒绝您的注册申请" :before-close="true"
                @close="closeFn('popTipApplyAgain')" @confirm="applyAgainFn" cancelText="确定" confirmText="重新申请">
            </uni-popup-dialog>
        </uni-popup>
    </view>
</template>

<script>
import { mapMutations, mapState } from "vuex"
import cardCellInput from "@/components/common/cell/card-cell-input.vue"
import { getUserInfo, getProductDisplay } from "@/utils/appInit.js"
import storage from "@/uni-sub-base/utils/storage.js"
import { getUserCarList } from "@/utils/cartUtil.js"
import config from "@/config/config.js"
import { mobileLogin } from "@/service/api/user.js"
import { getMiniProgramOpenId } from "@/service/api/weChat.js"
import { registerByWeixin, RegisterAndLogin } from "@/service/api/authorize.js"
import { AddLoginAuthApply } from "@/service/api/loginAuth.js"
import webViewUrl from "@/pages/micro/webViewUrl.js"
import { getLocation } from "@/uni-sub-base/utils/mapUtil.js"
export default {
    components: {
        cardCellInput,
    },
    data() {
        return {
            sessionKey: "",
            openId: "",
            nickName: null,
            avatarUrl: null,
            userInfo: {},
            data: "",
            isShow: false,
            url: "",
            showNav: false,
            location: null,
            userData: null,
            shopName: "",
        }
    },
    onLoad(e) {
        setTimeout(() => {
            this.showNav = true
            this.$forceUpdate()
        }, 300)
    },
    mounted() {
        this.shopName = this.getAppSet().shopName
    },
    methods: {
        ...mapMutations(["SET_AUTH"]),
        authorizeFn() {
            uni.getUserProfile({
                desc: "登录",
                success: (res) => {
                    this.userData = res
                    this.data = JSON.stringify(res)

                    this.getLocation()
                },
                fail: (res) => {
                    console.log(res)
                },
            })
        },
        //获取位置
        getLocationFn() {
            uni.getLocation({
                type: "wgs84",
                success: (res) => {
                    this.location = res
                    this.login()
                },
            })
        },
        //登录
        login() {
            let that = this
            // 获取登录用户code
            uni.login({
                provider: "weixin",
                success: function (res) {
                    if (res.code) {
                        let code = res.code
                        that.getOpenApi(res)
                    } else {
                        uni.showToast({
                            title: "登录失败！",
                            duration: 2000,
                        })
                    }
                },
            })
        },

        goHome(token) {
            this.SET_AUTH(token)
            let webInfo = storage.getCache("webInfo")
            if (webInfo) {
                this.url =
                    webInfo.WebDomain +
                    (webInfo.HomeIndex ? webInfo.HomeIndex : webViewUrl.url.home) +
                    "?uniToken=" +
                    token
            }
            this.isShow = true
            setTimeout((e) => {
                this.getUserInfo()
            }, 2500)
            getUserCarList()
            getProductDisplay().then((res) => { })
        },
        getUserInfo() {
            getUserInfo().then((res) => {
                uni.hideLoading()
                uni.reLaunch({
                    url: "/pages/index/index",
                })
            })
        },
        saveUserInfo(data) {
            storage.setCache("userInfo", data)
        },
        showLoginLoadding() {
            uni.showLoading({
                title: "登录中",
            })
        },
        //微信登录接口
        getOpenApi(data) {
            this.showLoginLoadding()
            let webInfo = storage.getCache("webInfo")
            let param = {
                code: data.code,
                businessId: webInfo.BusinessId,
                accId: webInfo.WxAccountId,
            }
            let path = "?code=" + data.code
            getMiniProgramOpenId(param, path).then((res) => {
                if (res.Data) {
                    this.loginByApi(res.Data)
                }
            })
        },
        //微信登录接口
        loginByApi(data) {
            let open_id = data.OpenId
            let union_id = data.UnionId || ""
            storage.setCache("openId", open_id)
            storage.setCache("unionId", union_id)
            let param = {
                open_id: open_id,
                union_id: union_id,
            }
            let lng = this.location.longitude
            let lat = this.location.latitude
            let province = this.location.address.province
            let city = this.location.address.city
            let area = this.location.address.district
            let face = this.userData.userInfo.avatarUrl
            let nick_name = this.userData.userInfo.nickName
            let path = `?open_id=${open_id}&union_id=${union_id}&nick_name=${nick_name}&face=${face}&province=${province}&city=${city}&area=${area}&lat=${lat}&lng=${lng}`
            RegisterAndLogin(param, path).then((res) => {
                uni.hideLoading()
                if (res.State == 1 && res.Data) {
                    let data = res.Data
                    this.userId = data.UserId
                    if (data.State == 0 && data.Token) {
                        //0表示正常(启用)
                        this.goHome(data.Token)
                    } else if (data.ApplyedLogin) {
                        //表示是否已经有了待审核的登录授权申请
                        this.$refs.popTipApplyOK.open()
                    } else if (data.State == 5) {
                        //5表示登录受限
                        this.$refs.popTipApply.open()
                    }
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        applyFn() {
            let webInfo = storage.getCache("webInfo")
            this.closeFn("popTipApply")
            //请求接口
            let param = {
                applyMessage: "申请",
                businessId: webInfo.BusinessId,
                userId: this.userId,
            }
            AddLoginAuthApply(param).then((res) => {
                if (res.State == 1) {
                    this.$refs.popTipApplyResult.open()
                }
            })
        },
        applyAgainFn() {
            this.closeFn("popTipApplyAgain")
            this.$refs.popTipApplyOK.open()
        },
        closeFn(type) {
            if (type == "popTipApplyResult") {
                this.$refs.popTipApplyResult.close()
            } else if (type == "popTipApply") {
                this.$refs.popTipApply.close()
            } else if (type == "popTipApplyOK") {
                this.$refs.popTipApplyOK.close()
            } else if (type == "popTipApplyAgain") {
                this.$refs.popTipApplyAgain.close()
            }
        },
        getLocation() {
            getLocation(
                (res) => {
                    if (res) {
                        this.location = res
                        this.login()
                    }
                },
                (error) => { },
            )
        },
    },
}
</script>

<style lang="scss">
page {
    background: $color-white;
}

.container {
    padding: 300rpx 60rpx 200rpx;
}

.login-wx {
    .business {
        display: flex;
        justify-content: center;
        border-bottom: solid 1rpx #cdcdcd;
        margin-bottom: 48rpx;
        padding-bottom: 48rpx;

        text {
            font-size: $font-size-44;
        }
    }

    .apply-tip {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .apply-tip-title {
            color: $color-black;
            font-size: $font-size-32;
            margin-bottom: 36rpx;
        }

        .apply-tip-desc {
            color: $app-color-text-desc;
            font-size: $font-size-26;
        }

        margin-bottom: 80rpx;
    }

    .btn {
        height: 80rpx;
        border-radius: 100rpx;
    }
}

.webView-mark {
    width: 100vw;
    height: 100vh;
    background: #fff;
    position: fixed;
    z-index: 999999999999;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
}

.webView-mark-load-text {
    margin-top: 300rpx;
}
</style>
